import Axios from 'axios';


const root = '/api/v1';

function toType (obj) {
    return ({}).toString.call(obj).match(/\s([a-zA-z]+)/)[1].toLowerCase();
}

function filterNull (o) {
    for (var key in o) {
        switch (true) {
            case o[key] === null:
                delete o[key];
                break;
            case toType(o[key]) === 'string':
                o[key] = o[key].trim();
                break;
            case toType(o[key]) === 'object':
                o[key] = filterNull(o[key]);
                break;
            case toType(o[key]) === 'array':
                o[key] = filterNull(o[key]);
                break;
        }
    }
    return o;
}

function apiAxios (method, url, params, success, failure) {
    params ? params = filterNull(params) : 0;
    Axios({
        method          : method,
        url             : url,
        data            : method === 'POST' || method === 'PUT'    ? params : null,
        params          : method === 'GET'  || method === 'DELETE' ? params : null,
        baseURL         : root,
        withCredentials : false
    }).then(
        (res) => {
            if (res.data.success === true) {
                if (success) {
                    success(res.data);
                }
            } else {
                if (failure) {
                    failure(res.data);
                } else {
                    window.alert('error: ' + JSON.stringify(res.data))
                }
            }
        }
    ).catch(
        (err) => {
            let res = err.response;
            if (err) {
                window.alert('api error, HTTP CODE: ' + res.status);
            }
        }
    )
}


export default {
    get    : function (url, params, success, failure) {
        return apiAxios('GET', url, params, success, failure);
    },
    post   : function (url, params, success, failure) {
        return apiAxios('POST', url, params, success, failure);
    },
    put    : function (url, params, success, failure) {
        return apiAxios('PUT', url, params, success, failure);
    },
    delete : function (url, params, success, failure) {
        return apiAxios('DELETE', url, params, success, failure);
    }
}




